package com.xoa.util.netdisk;

import com.xoa.model.netdisk.Catalog;
import com.xoa.model.netdisk.EasyUiDiskModel;
import com.xoa.model.netdisk.MyNetdisk;
import com.xoa.model.netdisk.Netdisk;
import com.xoa.model.users.Users;
import com.xoa.util.common.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.*;

public class ReadFile {

	//添加文件夹
	public static boolean mkDirectory(String path) {
		File file = null;
		try {
			file = new File(path);
			if (!file.exists()) {
				return file.mkdirs();
			} else{
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static Catalog getFiles(String fullPath,String path,String company){
		String url = fullPath + File.separator + path;
		ReadFile.getNetdiskPath();
		String urlxoa = url.replace(ReadFile.getNetdiskPath(),ReadFile.getNetdiskPath()+File.separator+company);
		File file=new File(url);
		//兼容旧数据
		if (!file.exists()){
			file = new File(urlxoa);
		}
		Catalog catalog=null;
		if (file.exists()){
			catalog=new Catalog();
			String dirSize="";
			int catalogcount=0;
			List<MyNetdisk> myNetdiskList=new ArrayList<MyNetdisk>();
			if (file.isDirectory()){//如果是个目录
				File[] files =file.listFiles();
				for (File fi:files){
					String pathUrl = fi.getAbsolutePath();
					MyNetdisk myNetdisk=new MyNetdisk();
					myNetdisk.setPath(path + File.separator +getFileName(pathUrl));
					myNetdisk.setNeName(getFileName(pathUrl));
					myNetdisk.setTime(getFileTime(fi));
					if (fi.isDirectory()){
						myNetdisk.setType("DIR");
						myNetdisk.setSize("");
					}else {
						myNetdisk.setType(getFileType(pathUrl));
						myNetdisk.setSize(FormetFileSize(getFileSizes(fi)));
					}
                    myNetdiskList.add(myNetdisk);
            }

			}else {
                dirSize=FormetFileSize(getFileSizes(file));

            }
            catalog.setCatalogcount(catalogcount);
            catalog.setCatalogSize(dirSize);
            catalog.setCatalogPath(url);
            catalog.setMyNetdiskList(myNetdiskList);


		}
		return  catalog;
	}


	//获取文件类型
	public static String getFileType(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();
	}
	//获取文件名
	public static String getFileName(String filePath) {
     String fileName="";
		//读取配置文件
		ResourceBundle rb =  ResourceBundle.getBundle("upload");
		String osName = System.getProperty("os.name");
		StringBuffer sb=new StringBuffer();
		if(osName.toLowerCase().startsWith("win")){
			String [] fileItems=filePath.split("\\\\");
			fileName=fileItems[fileItems.length-1];
		}else{
			String [] fileItems=filePath.split("/");
			fileName=fileItems[fileItems.length-1];
		}

		return fileName;
	}
	//获取文件时间
	public static Date getFileTime(File file){
		if(file==null||!file.exists()){
			return new Date();
		}
      return new Date(file.lastModified());
	}
	//获取文件时间
	public static Date getFileTime(String  filePath){
		File file =new File(filePath);
		if(!file.exists()){
			return new Date();
		}
		return new Date(file.lastModified());
	}
	//取得文件大小
	public static long getFileSizes(File f) {
		long s=0;
		FileChannel fc= null;
		FileInputStream fis=null;
		try {
			if (f.exists() && f.isFile()) {
				fis = new FileInputStream(f);
				fc = fis.getChannel();
				s = fc.size();
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if (null!=fc){
				try {
					fc.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}if (null!=fis){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
		return s;
	}
	//取得文件夹大小
	public static long getFileSize(File f)throws Exception
	{
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++)
		{
			if (flist[i].isDirectory())
			{
				size = size + getFileSize(flist[i]);
			} else
			{
				size = size + flist[i].length();
			}
		}
		return size;
	}
	public static String FormetFileSize(long fileS) {//转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if(fileS==0){
			return "0.00B";
		}
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}


	public static long getlist(File f){//递归求取目录文件个数
		long size = 0;
		File flist[] = f.listFiles();
		size=flist.length;
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getlist(flist[i]);
				size--;
			}
		}
		return size;

	}
	public static List<EasyUiDiskModel> getDirs(String dirPath) throws Exception{
		List<EasyUiDiskModel> res =null;
		File file=new File(dirPath);
		if (file.exists()){
			if (file.isDirectory()){//如果是个目录
				res=new ArrayList<EasyUiDiskModel>();
				File[] files =file.listFiles();
				int i=0;
				for (File fi:files){
					if(fi.isDirectory()){
						EasyUiDiskModel myNetdisk=new EasyUiDiskModel();
						String path=fi.getAbsolutePath();
						myNetdisk.setText(getFileName(path));
						myNetdisk.setId(i++);
						res.add(myNetdisk);
					}
				}
			}
		}
		return  res;
	}

	/**
	 * 创建人: liujian
	 * 创建时间: 2019/12/25
	 * 描述: 径获取网络硬盘全路径
	 * 参数: [path]
	 * 返回值: java.lang.String
	 */
	public static String getNetdiskPath(){
		//读取配置文件
		ResourceBundle rb =  ResourceBundle.getBundle("upload");
		String osName = System.getProperty("os.name");
		StringBuffer sb=new StringBuffer();
		if(osName.toLowerCase().startsWith("win")){
			//判断路径是否是相对路径，如果是的话，加上运行的路径
			String uploadPath = rb.getString("netdisk.win");
			if(uploadPath.indexOf(":")==-1){
				//获取运行时的路径
				String basePath = new Object() {
					public String getPath() {
						return this.getClass().getResource("").getPath();
					}
				}.getPath();
				//获取截取后的路径
				String str2 = "";
				if(basePath.indexOf("/xoa")!=-1){
					//返回指定字符在此字符串中第一次出现处的索引
					int index = basePath.indexOf("/xoa");
					//从指定位置开始到指定位置结束截取字符串
					str2=basePath.substring(0,index);
				}
				sb = sb.append(str2 + "/xoa");
			}
			sb.append(uploadPath);
		}else{
			sb=sb.append(rb.getString("netdisk.linux"));
		}
		return sb.toString();
	}

	/**
	 * 创建人  liujian
	 * 创建时间  2019/12/25
	 * 描述 网络硬盘判断权限方法
	 * 参数  [type, netdisk, users] 权限类型(1-管理，2-访问，3-新建，4-下载)
	 * 返回值  boolean
	 */
	public static boolean checkpurview(Integer type, Netdisk netdisk, Users users){
		boolean bol = false;
		String powers = null;
		switch (type){
			case 1:
				powers = netdisk.getManageUser();
				break;
			case 2:
				powers = netdisk.getUserId();
				break;
			case 3:
				powers = netdisk.getNewUser();
				break;
			case 4:
				powers = netdisk.getDownUser();
				break;
			default:
				return bol;
		}
		String[] checkStrings=(powers != null ? powers : "").split("\\|");
		String [] strTwo = null;
		for(int i = 0 ;i <checkStrings.length ;i++){
			if(!"".equals(checkStrings[i])){
				String[] check=checkStrings[i].split(",");
				switch (i){
					case 0:
						if("ALL_DEPT".equals(checkStrings[i]) || checkStrings[i].indexOf(users.getDeptId()+",") > -1){
							bol = true;
						}else{
							strTwo = users.getDeptIdOther().split(",");
						}
						break;
					case 1:
						if(checkStrings[i].indexOf(users.getUserPriv()+",") > -1){
							bol = true;
						}else{
							strTwo = users.getUserPrivOther().split(",");
						}
						break;
					case 2:
						if(checkStrings[i].indexOf(users.getUserId()+",") != -1){
							bol = true;
						}else{
							return bol;
						}
						break;
				}
				if(bol)return true;
				HashSet<String> set = new HashSet<>(Arrays.asList(strTwo));
				set.retainAll(Arrays.asList(check));
				if(set.size() > 0){
					bol =  true;
					break;
				}
			}
		}
		return bol;
	}


	/**
	 * 创建人  liujian
	 * 创建时间  2019/12/25
	 * 描述 网络硬盘判断权限方法
	 * 参数  [type, netdisk, users] 权限类型(1-管理，2-访问，3-新建，4-下载)
	 * 返回值  boolean
	 */
	public static boolean checkpurviews(Integer[] type, Netdisk netdisk, Users users){
		boolean bol = false;
		String powers = null;
		String[] checkStrings = new String [3];
		for(Integer integer : type){
			switch (integer){
				case 1:
					powers = netdisk.getManageUser();
					break;
				case 2:
					powers = netdisk.getUserId();
					break;
				case 3:
					powers = netdisk.getNewUser();
					break;
				case 4:
					powers = netdisk.getDownUser();
					break;
				default:
					return bol;
			}
			String[] Strings=(powers != null ? powers : "").split("\\|");
			for(int i = 0 ;i <Strings.length ;i++){
				checkStrings[i] += Strings[i];
			}
		}
		String [] strTwo = null;
		for(int i = 0 ;i <checkStrings.length ;i++){
			if(checkStrings[i] != null &&!"".equals(checkStrings[i])){
				String[] check=checkStrings[i].split(",");
				switch (i){
					case 0:
						if("ALL_DEPT".equals(checkStrings[i]) || checkStrings[i].indexOf(users.getDeptId()+",") > -1){
							bol = true;
						}else{
							strTwo = users.getDeptIdOther().split(",");
						}
						break;
					case 1:
						if(checkStrings[i].indexOf(users.getUserPriv()+",") > -1){
							bol = true;
						}else{
							strTwo = users.getUserPrivOther().split(",");
						}
						break;
					case 2:
						if(checkStrings[i].indexOf(users.getUserId()+",") != -1){
							bol = true;
						}else{
							return bol;
						}
						break;
				}
				if(bol)return true;
				HashSet<String> set = new HashSet<>(Arrays.asList(strTwo));
				set.retainAll(Arrays.asList(check));
				if(set.size() > 0){
					bol =  true;
					break;
				}
			}
		}
		return bol;
	}


	/**
	 * 创建人: liujian
	 * 创建时间: 2019/12/25
	 * 描述: 查询文件夹下所有文件详情
	 * 参数: [fullPath] 全路径 ， [path]文件需要回显的路径
	 * 返回值: java.util.List<com.xoa.model.netdisk.MyNetdisk>
	 */
    public static List<MyNetdisk> getFilesInPath(String fullPath,String path) throws Exception{
		List<MyNetdisk> res =null;
		File file=new File(fullPath);
		if (file.exists()){
			if (file.isDirectory()){//如果是个目录
				res=	new ArrayList<MyNetdisk>();
				File[] files =file.listFiles();
				for (File fi:files){
					if(fi.isFile()){
						MyNetdisk myNetdisk=new MyNetdisk();
						String filepath=fi.getAbsolutePath();
						myNetdisk.setPath(path+File.separator+getFileName(filepath));
						//判断是否加密（文件名去除后缀并回传加密类型）
						if("XOAFILE".equals(getFileType(filepath))){
							filepath = filepath.substring(0,filepath.lastIndexOf(".xoafile"));
							myNetdisk.setEncryType(".xoafile");
						}
						myNetdisk.setSizeNum(getFileSizes(fi));
						myNetdisk.setSize(FormetFileSize(getFileSizes(fi)));
						myNetdisk.setTime(getFileLastModifed(fi));
						myNetdisk.setType(getFileType(filepath));
						myNetdisk.setNeName(getFileName(filepath));
						res.add(myNetdisk);
					}
				}
			}else{
				if(file.isFile()){
					res=	new ArrayList<MyNetdisk>();

					MyNetdisk myNetdisk=new MyNetdisk();
					String filepath=file.getAbsolutePath();
					myNetdisk.setPath(path+File.separator+getFileName(filepath));
					//判断是否加密（文件名去除后缀并回传加密类型）
					if("XOAFILE".equals(getFileType(filepath))){
						filepath = filepath.substring(0,filepath.lastIndexOf(".xoafile"));
						myNetdisk.setEncryType(".xoafile");
					}
					myNetdisk.setSizeNum(getFileSizes(file));
					myNetdisk.setSize(FormetFileSize(getFileSizes(file)));
					myNetdisk.setTime(getFileLastModifed(file));
					myNetdisk.setType(getFileType(filepath));
					myNetdisk.setNeName(getFileName(filepath));
					res.add(myNetdisk);
				}
			}
		}
		return  res;
    }

    public static Date getFileLastModifed(File file) throws FileNotFoundException {
		if(!file.exists()){
			throw new FileNotFoundException();
		}
	    long time =	file.lastModified();
		Date date = new Date(time);
		return date;
	}

	/**
	 *
	 * @作者 李卫卫
	 * @创建日期 13:55 2020/11/30
	 * @类介绍  径获取公共文件柜存放附件全路径
	 * @参数
	 * @return limsJson
	 */

	public static String getFilePath(){
		//读取配置文件
		//ResourceBundle rb =  ResourceBundle.getBundle("upload");
		String osName = System.getProperty("os.name");
		StringBuffer sb=new StringBuffer();
		if(osName.toLowerCase().startsWith("win")){
			//判断路径是否是相对路径，如果是的话，加上运行的路径a
			String uploadPath = "/attach";
			if(uploadPath.indexOf(":")==-1){
				//获取运行时的路径
				String basePath = new Object() {
					public String getPath() {
						return this.getClass().getResource("").getPath();
					}
				}.getPath();
				//获取截取后的路径
				String str2 = "";
				if(basePath.indexOf("/xoa")!=-1){
					//返回指定字符在此字符串中第一次出现处的索引
					int index = basePath.indexOf("/xoa");
					//从指定位置开始到指定位置结束截取字符串
					str2=basePath.substring(0,index);
				}
				sb = sb.append(str2 + "/xoa");
			}
			sb.append(uploadPath);
		}else{
			sb=sb.append("/xoa/attach");
		}
		return sb.toString();
	}
}
